﻿'***********************************************************************
' Assembly         : SOFA.Caching
' Copyright        : (c) Jebarson. All rights reserved.
' Website			: http://www.jebarson.info
'***********************************************************************

Option Strict Off

Imports System.Linq.Enumerable
Imports System.Threading.Tasks
Namespace Caching.Recycler
    ''' <summary>
    ''' Manager for recycling the cache.
    ''' </summary>
    Friend NotInheritable Class RecycleManager
        Inherits TaskFactory

#Region " Constructors "
        ''' <summary>
        ''' Prevents a new instance of the <see cref="RecycleManager" /> class.
        ''' </summary>
        Private Sub New()
        End Sub
#End Region

#Region " Public Methods "
        ''' <summary>
        ''' Checks the expiry.
        ''' </summary>
        ''' <typeparam name="T"></typeparam>
        ''' <param name="itemEntry">The item entry.</param>
        ''' <param name="item">The cached item.</param>
        Public Shared Sub CheckExpiry(Of T As StorageItemEntry)(ByRef itemEntry As StorageItemEntry, ByVal item As StorageItemCollection(Of T))

            If (itemEntry.ExpiryTime > DateTime.Now) Then
                Exit Sub
            End If

            ' Check if the whole lookup is expired.
            If (GetExpiredStorageItemEntries(item).Count = item.Count) Then
                item.StorageFactory.SetStorageItem(item, True)
                itemEntry = item.Item(itemEntry.Key)
            Else
                itemEntry = item.Load(itemEntry.Key)
                CacheStorageFactory(Of ICacheStorageConfig).InitializeStorageItemEntry(itemEntry, item.StorageConfig)
            End If
        End Sub
#End Region

#Region " Private Methods "
        ''' <summary>
        ''' Gets the expired storage item entries.
        ''' </summary>
        ''' <typeparam name="T"></typeparam>
        ''' <param name="item">The item.</param>
        ''' <returns>The expired storage items.</returns>
        Private Shared Function GetExpiredStorageItemEntries(Of T As StorageItemEntry)(ByVal item As StorageItemCollection(Of T)) As IList(Of StorageItemEntry)

            Return item.ItemEntries.Where(Function(itemEntry As StorageItemEntry) itemEntry.ExpiryTime <= DateTime.Now()).ToList()
        End Function
#End Region

    End Class
End Namespace